package domein;

import java.net.InetAddress;
import java.util.*;

/**
 * 
 * @author rensbonnez
 *
 */

public class Peer 
{
	private InetAddress ipAddress;
	private String peerName;
	private List<PeerFile> peerFiles = new ArrayList<PeerFile>();
	
	/**
	 * Constructor
	 * @param ipAddress
	 * @param peerName
	 */
	public Peer(InetAddress ipAddress, String peerName)
	{
		setIpAddress(ipAddress);
		setPeerName(peerName);
	}
	
	/**
	 * Constructor
	 * @param ipAddress
	 * @param peerName
	 * @param peerFiles
	 */
	
	public Peer(InetAddress ipAddress, String peerName, List<PeerFile> peerFiles)
	{
		this(ipAddress, peerName);
		setPeerFiles(peerFiles);
	}
	
	public String getFilesAsString()
	{
		String stringFiles = "";
		
		//Separators uses: <PS> --> ParamSplitter, <FS> --> FileSplitter
		for (PeerFile peerFile : peerFiles) 
		{
			stringFiles += String.format("%d<PS>%s<PS>%d<PS>%s", peerFile.getFileId(), peerFile.getFileName(), peerFile.getFileSize(), peerFile.getPeerIp());
			
			if(peerFiles.indexOf(peerFile) != peerFiles.size()-1)
			{
				stringFiles += String.format("<FS>");
			}
		}
		
		return stringFiles;
	}
	
	public List<PeerFile> getPeerFiles() {
		List<PeerFile> allPeerFiles = new LinkedList<PeerFile>();
		allPeerFiles.addAll(peerFiles);

	    Collections.sort(allPeerFiles, new Comparator<PeerFile>() 
	    {
	    	public int compare(PeerFile peerFile1, PeerFile peerFile2)
	    	{
	    		String name1 = peerFile1.getFileName().toLowerCase();
	    		String name2 = peerFile2.getFileName().toLowerCase();
	    		
	    		return name1.compareTo(name2);
	    	}
		});
	    
	    return allPeerFiles;
	}
	
	public String[] toArray() 
	{
		String[] array = new String[2];
		array[0] = peerName;
		array[1] = ipAddress.toString() ;
		
		return array;
	}
	
	/**
	 * 
	 * Getters & Setters
	 * 
	 */

	public InetAddress getIpAddress() {
		return ipAddress;
	}

	public void setIpAddress(InetAddress ipAddress) {
		this.ipAddress = ipAddress;
	}

	public void setPeerFiles(List<PeerFile> peerFiles) {
		this.peerFiles = peerFiles;
	}

	public String getPeerName() {
		return peerName;
	}

	public void setPeerName(String peerName) {
		this.peerName = peerName;
	}
}
